package cn.edu.nju.newsFeed;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import cn.edu.nju.R;
import cn.edu.nju.sharing.StartUpActivity;

import android.app.Activity;
import android.text.format.DateFormat;
import android.widget.Toast;

public class PostSender {
	private Activity activity;
	private int mode;
	private String serverUrl;
	private long senderId;
	private long newsId;

	private Calendar dueTime;
	private String content;
	private List<File> images;
	
	private List<String> tags;

	public PostSender(Activity activity, int mode, long senderId) {
		this.activity = activity;
		this.mode = mode;
		this.senderId = senderId;

		serverUrl = activity.getString(R.string.server_url) + "send.php";
	}

	public void setDueTime(Calendar date) {
		this.dueTime = date;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public void setImages(List<File> files) {
		this.images = files;
	}

	public void setNewsFeedId(long id) {
		this.newsId = id;
	}
	
	public void setTags(List<String> tags){
		this.tags = tags;
	}

	public boolean send() {
		if (mode == WritePostActivity.FEED_MODE) {
			return feed();
		} else if (mode == WritePostActivity.COMMENT_MODE) {
			return comment();
		}
		return false;
	}

	// Only used in the feed mode
	private boolean feed() {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			entity.addPart("id", new StringBody("" + senderId));
			entity.addPart("option", new StringBody("news"));
			entity.addPart("num",new StringBody("" + tags.size(), Charset.forName("utf-8")));
			
			for (int i = 0; i < tags.size(); i++) {
				entity.addPart("tag" + i,new StringBody(tags.get(i),Charset.forName("utf-8")));
			}

			String pattern = "yyyy-MM-dd hh:mm:ss";
			entity.addPart(
					"time",
					new StringBody(
							""
									+ DateFormat.format(pattern,
											Calendar.getInstance())));

			entity.addPart("due_time",
					new StringBody("" + DateFormat.format(pattern, dueTime)));
			entity.addPart("content", new StringBody(content,Charset.forName("utf-8")));

			if (StartUpActivity.latitude == 0 || StartUpActivity.longitude == 0) {
				Toast.makeText(activity, "LBS Failure", 100000).show();
				return false;
			}
			entity.addPart("latitude", new StringBody(""
					+ StartUpActivity.latitude));
			entity.addPart("longitude", new StringBody(""
					+ StartUpActivity.longitude));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			// Toast.makeText(activity,"Feed: " + context, 100000).show();

			if (context.equals(new String("fail"))) {
				return false;
			}

			setNewsFeedId(Long.parseLong(context));

			if (images.size() != 0) {
				if (!commitImages()) {
					return false;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	// Only used in the comment mode
	private boolean comment() {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			entity.addPart("option", new StringBody("comment"));
			entity.addPart("id", new StringBody("" + senderId));
			entity.addPart("news_id", new StringBody("" + newsId));
			entity.addPart("content", new StringBody(content,Charset.forName("utf-8")));

			String pattern = "yyyy-MM-dd hh:mm:ss";
			entity.addPart(
					"time",
					new StringBody(
							""
									+ DateFormat.format(pattern,
											Calendar.getInstance())));

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			// Toast.makeText(activity,"Comment: " + context, 100000).show();

			if (context.equals(new String("fail"))) {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}

	// Only used to commit images
	private boolean commitImages() {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost post = new HttpPost(serverUrl);

			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			entity.addPart("option", new StringBody("image"));
			entity.addPart("id", new StringBody("" + newsId));
			entity.addPart("num", new StringBody("" + images.size()));

			for (int i = 0; i < images.size(); i++) {
				entity.addPart("file" + i, new FileBody(images.get(i)));
			}

			post.setEntity(entity);

			HttpResponse response = client.execute(post, localContext);
			HttpEntity httpEntity = response.getEntity();
			InputStream input = httpEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					input));

			String context = reader.readLine();
			reader.close();

			// Toast.makeText(activity,"Image: " + context, 100000).show();

			if (context.equals(new String("fail"))) {
				return false;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return true;
	}
}
